package com.gitee.wsl.struct.grammar.parser.context.ext

import com.gitee.wsl.struct.grammar.parser.Parser
import com.gitee.wsl.struct.grammar.parser.ParsingScope
import com.gitee.wsl.struct.grammar.parser.combinator.ignored
import com.gitee.wsl.struct.grammar.parser.combinator.poll
import com.gitee.wsl.struct.grammar.parser.combinator.times

suspend fun <T : Any> ParsingScope.split(
    term: Parser<T>,
    separator: Parser<Any>,
    allowEmpty: Boolean = true,
    trailingSeparator: Boolean = false,
): List<T> {
    val values = mutableListOf<T>()
    values += if (!allowEmpty) term() else poll(term) ?: return emptyList()
    values += repeat(ignored(separator) * term, atLeast = 0)
    if (trailingSeparator) {
        poll(separator)
    }
    return values
}